package ${serviceClazz?lower_case};

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.util.Assert;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import ${serviceClazz?lower_case}.dto.${serviceName?cap_first}UpdateReq;
import ${serviceClazz?lower_case}.dto.${serviceName?cap_first}AddReq;
import ${serviceClazz?lower_case}.dto.${serviceName?cap_first}QueryFilter;
import ${mapperClazz};
import ${modelClazz};
import ${modelClazz}Example;
import ${modelClazz}Example.Criteria;
import com.system.core.security.NameUtil;
import com.system.core.utils.Money;
import com.system.core.utils.BeanUtil;
import com.system.core.view.common.response.CommonDataResponse;
import com.system.core.view.common.response.CommonPageResponse;
import com.system.core.view.common.response.CommonResponse;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

@Service
@Slf4j
@RequiredArgsConstructor
@Validated
/**
 * ${tableInfo.tableComment}服务
 */
public class ${serviceName?cap_first}Service {
	
	private SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	<#list columns as item>
	<#if item.prikey>
	<#assign priname="${item.javaCode?cap_first}"/>
	<#assign priType="${item.javaType}"/>
	</#if>
	</#list>
	
	private final ${modelName}Mapper ${modelName?uncap_first}Mapper;
	
	/**
	 * 获取所有${modelName}
	 */
	public CommonDataResponse<List<${modelName}>> ${serviceName?uncap_first}ListAll(){
		return CommonDataResponse.buildSuccessResult(${modelName?uncap_first}Mapper.selectByExample(null));
	}
	
	/**
	 * 页面列表查询
	 * @return
	 */
	public CommonPageResponse<${modelName}> ${serviceName?uncap_first}List(${serviceName?cap_first}QueryFilter filter) throws Exception{
		log.debug("[${modelName?uncap_first}]查询入参：{}",filter);
		${modelName}Example ${modelName?uncap_first}Example = getQueryFilterExample(filter);
		// 排序
		if(StringUtils.isNotBlank(filter.getOrderField())) {
			${modelName?uncap_first}Example.setOrderByClause(NameUtil.javaName2_(filter.getOrderField())+" "+filter.getOrderType());
        } else {
        	${modelName?uncap_first}Example.setOrderByClause("create_time desc");
        }
		//在此插入查询条件end
		
		Page<${modelName}> page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		List<${modelName}> list = ${modelName?uncap_first}Mapper.selectByExample(${modelName?uncap_first}Example);
		CommonPageResponse<${modelName}> pageResult = CommonPageResponse.buildSuccessResult(page.getTotal(), list);
		return pageResult;
	}
	
	/**
	 * 根据主键获取单条数据
	 * @param ${priname?uncap_first} 主键
	 */
	public CommonDataResponse<${modelName}> ${serviceName?uncap_first}GetByPrimaryKey(${priType} ${priname?uncap_first}) {
		${modelName?cap_first} result = ${modelName?uncap_first}Mapper.selectByPrimaryKey(${priname?uncap_first});
		return CommonDataResponse.buildSuccessResult(result);
	}
	
	/**
	 * 根据主键更新数据
	 * @param ${modelName?uncap_first} 被更新对象（请注意，只更新有值属性）
	 */
	public CommonResponse ${serviceName?uncap_first}UpdateByPrimaryKey(${serviceName?cap_first}UpdateReq ${serviceName?uncap_first}UpdateReq) {
		${modelName?cap_first} ${modelName?uncap_first} = BeanUtil.copyBeanFromNew(${serviceName?uncap_first}UpdateReq,${modelName?cap_first}.class);
		<#list columns as item>
		<#if (item.columnType?index_of('decimal') >= 0)>
		<#if (item.getDecimalScale() == 2)>
		if(${serviceName?uncap_first}UpdateReq.get${item.javaCode?cap_first}()!=null)
		${modelName?uncap_first}.set${item.javaCode?cap_first}(new Money(${serviceName?uncap_first}UpdateReq.get${item.javaCode?cap_first}()));
		</#if>
		</#if>
		</#list>
		${modelName?uncap_first}Mapper.updateByPrimaryKeySelective(${modelName?uncap_first});
		return CommonResponse.buildSuccessResult("更新成功");
	}
	
	/**
	 * 根据主键删除数据
	 * @param keys 被删除对象主键List集合
	 */
	@Transactional
	public CommonResponse ${serviceName?uncap_first}DeleteByPrimaryKey(List<${priType}> keys) {
		LongAdder counter = new LongAdder();
		keys.forEach((key)->{
			int i;i = ${modelName?uncap_first}Mapper.deleteByPrimaryKey(key);
			if(i > 0)
				counter.increment();
		});
		return CommonResponse.buildSuccessResult("成功删除"+counter.intValue()+"条记录");
	}
	
	/**
	 * 新增数据
	 * @param ${modelName?uncap_first}AddReqDto 新增对象
	 */
	@Transactional
	public CommonResponse ${serviceName?uncap_first}Save(${serviceName?cap_first}AddReq ${serviceName?uncap_first}AddReq) {
		${modelName?cap_first} ${modelName?uncap_first} = BeanUtil.copyBeanFromNew(${serviceName?uncap_first}AddReq, ${modelName?cap_first}.class);
		<#list columns as item>
		<#if (item.columnType?index_of('decimal') >= 0)>
		<#if (item.getDecimalScale() == 2)>
		${modelName?uncap_first}.set${item.javaCode?cap_first}(new Money(${serviceName?uncap_first}AddReq.get${item.javaCode?cap_first}()));
		</#if>
		</#if>
		</#list>
		int savedRow = ${modelName?uncap_first}Mapper.insertSelective(${modelName?uncap_first});
		Assert.isTrue(savedRow > 0 , "新增失败！");
		return CommonResponse.buildSuccessResult("新增成功");
	}
	
	private ${modelName}Example getQueryFilterExample(${serviceName?cap_first}QueryFilter filter) throws ParseException {
		${modelName}Example ${modelName?uncap_first}Example = new ${modelName}Example();
		Criteria criteria = ${modelName?uncap_first}Example.createCriteria();
		//在此插入查询条件start
		<#list columns as item>
		<#if (item.columnType?index_of('varchar') >= 0) 
			|| (item.columnType?index_of('text') >= 0)>
		if(StringUtils.isNotBlank(filter.get${item.javaCode?cap_first}())) {
			criteria.and${item.javaCode?cap_first}EqualTo(filter.get${item.javaCode?cap_first}());
		}
		</#if>
		<#if (item.columnType?index_of('timestamp') >= 0) || (item.columnType?index_of('datetime') >= 0)>
		/**
		 * ${item.javaCode}字段时间范围查找，从${item.javaCode}${TIMESTARTSTR}到${item.javaCode}${TIMEENDSTR}之间时间范围
		 */
		if(StringUtils.isNotBlank(filter.get${item.javaCode?cap_first}${TIMESTARTSTR}())) {
			criteria.and${item.javaCode?cap_first}GreaterThanOrEqualTo(timeformat.parse(filter.get${item.javaCode?cap_first}${TIMESTARTSTR}()));
		}
		if(StringUtils.isNotBlank(filter.get${item.javaCode?cap_first}${TIMEENDSTR}())) {
			criteria.and${item.javaCode?cap_first}LessThanOrEqualTo(timeformat.parse(filter.get${item.javaCode?cap_first}${TIMEENDSTR}()));
		}
		</#if>
		<#if (item.columnType?index_of('int') >= 0)
			||(item.columnType?index_of('enum') >= 0)>
		if(filter.get${item.javaCode?cap_first}() != null) {
			criteria.and${item.javaCode?cap_first}EqualTo(filter.get${item.javaCode?cap_first}());
		}
		</#if>
		<#if (item.columnType?index_of('decimal') >= 0)>
		if(filter.get${item.javaCode?cap_first}() != null) {
		<#if (item.getDecimalScale() == 2)>
			criteria.and${item.javaCode?cap_first}EqualTo(new Money(filter.get${item.javaCode?cap_first}()));
		<#elseif (item.getDecimalScale() == 0)>
			criteria.and${item.javaCode?cap_first}EqualTo(BigDecimal.valueOf(filter.get${item.javaCode?cap_first}().doubleValue()));
		<#elseif (item.getDecimalScale() == 8)>
			criteria.and${item.javaCode?cap_first}EqualTo(DigitAssets.num(filter.get${item.javaCode?cap_first}().doubleValue()));
		</#if>
		}
		</#if>
		</#list>
		return ${modelName?uncap_first}Example;
	}
}
